import api from '@/store/api';
import i18n from '@/i18n';
const { t } = i18n.global as any;

export const useDateTimeStoreStore = defineStore('dateTimeStore', () => {
  const ntpServers = ref([] as any[]);
  const isNtpProtocolEnabled = ref(null);

  const setNtpServers = (Servers: any) => (ntpServers.value = Servers);
  const setIsNtpProtocolEnabled = (isEnabled: any) =>
    (isNtpProtocolEnabled.value = isEnabled);

  const getNtpData = async () => {
    return await api
      .get('/redfish/v1/Managers/bmc/NetworkProtocol')
      .then((response) => {
        const ntpServers = response.data.NTP.NTPServers;
        const isNtpProtocolEnabled = response.data.NTP.ProtocolEnabled;
        setNtpServers(ntpServers);
        setIsNtpProtocolEnabled(isNtpProtocolEnabled);
      })
      .catch((error) => {
        console.log(error);
      });
  };
  const updateDateTime = async (dateTimeForm: {
    ntpProtocolEnabled?: any;
    ntpServersArray?: any;
    updatedDateTime?: any;
  }) => {
    const ntpData: {
      NTP: {
        ProtocolEnabled: boolean;
        NTPServers?: (typeof dateTimeForm.ntpServersArray)[];
      };
    } = {
      NTP: {
        ProtocolEnabled: dateTimeForm.ntpProtocolEnabled,
      },
    };
    if (dateTimeForm.ntpProtocolEnabled) {
      ntpData.NTP.NTPServers = dateTimeForm.ntpServersArray;
    }
    return await api
      .patch(`/redfish/v1/Managers/bmc/NetworkProtocol`, ntpData)
      .then(async () => {
        if (!dateTimeForm.ntpProtocolEnabled) {
          const dateTimeData = {
            DateTime: dateTimeForm.updatedDateTime,
          };
          const timeoutVal = isNtpProtocolEnabled.value ? 20000 : 0;
          return await new Promise<void>((resolve, reject) => {
            setTimeout(() => {
              return api
                .patch(`/redfish/v1/Managers/bmc`, dateTimeData)
                .then(() => resolve())
                .catch(() => reject());
            }, timeoutVal);
          });
        }
      })
      .then(() => {
        return t('pageDateTime.toast.successSaveDateTime');
      })
      .catch((error) => {
        console.log(error);
        throw new Error(t('pageDateTime.toast.errorSaveDateTime') as string);
      });
  };

  return {
    ntpServers,
    isNtpProtocolEnabled,
    setNtpServers,
    setIsNtpProtocolEnabled,
    getNtpData,
    updateDateTime,
  };
});
